package com.example.zzy.zzytest.data.structure.stack;

import java.util.Scanner;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(3);
        System.out.println("操作包括push:pop:list");

        Scanner scanner = new Scanner(System.in);
        while(true){

            String next = scanner.next();
            switch (next){
                case "push":
                    System.out.println("输入入栈数值：");
                    int value = scanner.nextInt();
                    arrayStack.pushStack(value);
                    break;
                case "pop":
                    arrayStack.popStack();
                    break;
                case "list":
                    arrayStack.list();
                    break;
                default:
                    scanner.close();
                    System.out.println("程序退出");
                    break;
            }
        }
    }
}

class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[maxSize];
    }

    //栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    //栈空
    public boolean isEmpty() {
        return top == -1;
    }

    //入栈
    public void pushStack(int num) {
        if (isFull()) {
            System.out.println("栈已满，入栈失败");
            return;
        }
        top++;
        this.stack[top] = num;
    }

    //出栈
    public void popStack() {
        if (isEmpty()) {
            System.out.println("栈为空，出栈失败");
            return;
        }
        System.out.println("本次出栈>>>" + this.stack[top--]);

    }

    //遍历
    public void list() {
        for (int i = top; i >= 0; i--) {
            System.out.println(this.stack[i] + "\t");
        }
    }
}
